package com.wanxi.dao.Impl;

import com.wanxi.dao.ImageDao;
import com.wanxi.model.Image;
import com.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ImageDaoImpl implements ImageDao {
    @Override
    public List<Image> findAllImage() {
        List<Image> list=new ArrayList<>();
        String sql="select * from image";
        ResultSet query = JDBC.query(sql);
        try {
            while (query.next()){
                list.add(Image.builder()
                        .id(query.getInt("id"))
                        .imageLocation(query.getString("imageLocation"))
                        .enable(query.getInt("enable"))
                        .createTime(query.getTimestamp("createTime"))
                        .updateTime(query.getTimestamp("updateTime"))
                        .remark(query.getString("remark")).build());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public Image findImageById(Image image) {
        String sql="select * from image where id="+image.getId();
        ResultSet query = JDBC.query(sql);
        try {
            while (query.next()){
                return Image.builder()
                        .id(query.getInt("id"))
                        .imageLocation(query.getString("imageLocation"))
                        .enable(query.getInt("enable"))
                        .createTime(query.getTimestamp("createTime"))
                        .updateTime(query.getTimestamp("updateTime"))
                        .remark(query.getString("remark"))
                        .build();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public int updateEnable(Image image) {
        String sql="update image set enable="+image.getEnable()+",updateTime=(select now()) where id="+image.getId();
        return JDBC.update(sql);
    }

    @Override
    public int addImage(Image image) {
        String sql="insert into image(imageLocation,enable,createTime,updateTime,remark) "
                +"values('"+image.getImageLocation()
                +"',"+image.getEnable()
                +",(select now()),(select now()),'"+image.getRemark()
                +"')";
        return JDBC.update(sql);
    }

    @Override
    public int deleteImage(Image image) {
        String sql="delete from image where id="+image.getId();
        return JDBC.update(sql);
    }

    @Override
    public int update(Image image) {
        String sql="update image set imageLocation='"+image.getImageLocation()
                +"',enable="+image.getEnable()
                +",remark='"+image.getRemark()
                +"',updateTime=(select now()) where id="+image.getId();
        return JDBC.update(sql);
    }
}
